'use strict';
let uniID = require('uni-id')
const db = uniCloud.database();
const integral = db.collection('integral');
exports.main = async (event, context) => {
	uniID = uniID.createInstance({
		context
	})
	let params = event.params || {}
	let payload = {}
	var data_eve = {}
	if (!event.uniIdToken) {
		return {
			code: 403,
			msg: '缺少token'
		}
	}
	payload = await uniID.checkToken(event.uniIdToken, {
		needPermission: true
	})
	if (payload.code && payload.code > 0) {
		return payload
	}
	params.uid = payload.uid
	const {
		userInfo,
	} = await uniID.checkToken(event.uniIdToken, {
		needPermission: true
	})
	let res = {}
	var nowtime = new Date().getTime()
	if (userInfo.endTime && userInfo.endTime < nowtime) {
		const {
			uid,
		} = params
		res = await uniID.updateUser({
			uid,
			endTime: null,
			isvip: 0
		});
		return {
			code: 0,
			msg: "会员已过期"
		}
	}

	if ((userInfo.number == 0 || userInfo.number < 0) && userInfo.isvip == 0) {
		data_eve = {
			code: 400,
			msg: "次数已用尽,或会员已到期",
			number: userInfo.number
		}
		return data_eve
	}



	const {
		msg,
	} = event


	const apikey = await db.collection('apiKey').where({
		is_open: 1
	}).get()
	// apikey.data[0].apikey,

	var apiurl = 'https://api.openai.com/'

	var apiopen = {}

	switch (event.type) {
		case 'chat': {
			apiopen = {
				url: apiurl + 'v1/chat/completions',
				openaikey: "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",
				msg: {
					messages: event.data,
					model: 'gpt-3.5-turbo'
				}
			}
			break;
		}
		case 'quota': {
			apiopen = {
				url: apiurl + 'dashboard/billing/credit_grants',
				openaikey: apikey.data[0].apikey,
			}
			break;
		}
		case 'dianping': {
			apiopen = {
				url: 'https://api.openai.com/v1/completions',
				openaikey: apikey.data[0].apikey,
				msg: {
					model: "text-davinci-003",
					prompt: event.data,
					max_tokens: 2048,
					temperature: 0.5,
					max_tokens: 2048,
					top_p: 1.0,
					frequency_penalty: 0.0,
					presence_penalty: 0.0,
				}
			}
			break;
		}
		case 'color': {
			apiopen = {
				url: 'https://api.openai.com/v1/completions',
				openaikey: apikey.data[0].apikey,
				msg: {
					model: "text-davinci-003",
					prompt: event.data,
					max_tokens: 2048,
					temperature: 0.8,
					max_tokens: 60,
					top_p: 1.0,
					frequency_penalty: 0.5,
					presence_penalty: 0.0,
				}
			}
			break;
		}
		case 'kongbu': {
			apiopen = {
				url: 'https://api.openai.com/v1/completions',
				openaikey: apikey.data[0].apikey,
				msg: {
					model: "text-davinci-003",
					prompt: event.data,
					temperature: 0,
					max_tokens: 2048,
					top_p: 1.0,
					frequency_penalty: 0.0,
					presence_penalty: 0.0,
					stop: [";"],
				}
			}
			break;
		}
		case 'fanyi': {
			apiopen = {
				url: 'https://api.openai.com/v1/completions',
				openaikey: apikey.data[0].apikey,
				msg: {
					model: "text-davinci-003",
					prompt: event.data,
					temperature: 0,
					max_tokens: 2048,
					top_p: 1.0,
					frequency_penalty: 0.0,
					presence_penalty: 0.0,
				}
			}
			break;
		}
		case 'image': {
			apiopen = {
				url: 'https://api.openai.com/v1/images/generations',
				openaikey: apikey.data[0].apikey,
				msg: {
					prompt: event.data,
					n: 1,
					size: "1024x1024"
				}
			}
			break;
		}
		case 'javaScript': {
			apiopen = {
				url: 'https://api.openai.com/v1/completions',
				openaikey: apikey.data[0].apikey,
				msg: {
					model: "code-davinci-002",
					prompt: event.data,
					temperature: 0,
					max_tokens: 2048,
					top_p: 1.0,
					frequency_penalty: 0.5,
					presence_penalty: 0.0,
					stop: ["You:"]
				}
			}
			break;
		}
	}
	console.log(apiopen);
	const openai_res = await uniCloud.httpclient.request(
		'http://154.40.38.217:3000/chat', {
			method: 'POST',
			data: apiopen, // 请求内容
			timeout: 100000,
			contentType: 'json',
			dataType: 'json',
		})

	console.log(openai_res);
	// const ed = await uniCloud.httpclient.request(
	// 	'http://104.168.158.146:3000', {
	// 		method: 'POST',
	// 		data: {
	// 			openaikey: apikey.data[0].apikey
	// 		}, // 请求内容
	// 		timeout: 100000,
	// 		contentType: 'json',
	// 		dataType: 'json', // 此处指定为json表示将此请求的返回值解析为json
	// 	})
	if (openai_res.data.code == 200) {
		const {
			uid,
		} = params
		if (userInfo.isvip == 0) {
			res = await uniID.updateUser({
				uid,
				number: userInfo.number - 1,
				openNum: userInfo.openNum + 1,
			});
			const integral_A = await integral.add({
				uid,
				name: "AI对话消耗",
				color: 'purplered',
				integral: '-' + String(1),
				time: new Date().getTime()
			})
		} else {
			res = await uniID.updateUser({
				uid,
				openNum: userInfo.openNum + 1,
			});
		}
		var openai = openai_res.data.data
		var text = ''
		switch (event.type) {
			case 'chat': {
				text = openai.choices[0].message.content.replace("openai:", "").replace(
						"openai：", "")
					.replace(/^\n|\n$/g, "")
				break;
			}
			case 'fanyi': {
				text = openai.choices[0].text.replace("openai:", "").replace(
						"openai：", "")
					.replace(/^\n|\n$/g, "")
				break;
			}
			case 'dianping': {
				text = openai.choices[0].text.replace("openai:", "").replace(
						"openai：", "")
					.replace(/^\n|\n$/g, "")
				break;
			}
			case 'kongbu': {
				text = openai.choices[0].text.replace("openai:", "").replace(
						"openai：", "")
					.replace(/^\n|\n$/g, "")
				break;
			}
			case 'color': {
				text = openai.choices[0].text.replace("openai:", "").replace(
						"openai：", "")
					.replace(/^\n|\n$/g, "")
				break;
			}
			case 'javaScript': {
				text = openai.choices[0].text.replace("openai:", "").replace(
						"openai：", "")
					.replace(/^\n|\n$/g, "")
				break;
			}
			case 'image': {
				console.log("openai_res.data---》",openai_res.data)
				text = openai_res.data.data.data[0].url
				break;
			}

		}
		// await db.collection('apiKey').doc(String(apikey.data[0]._id)).update({
		// 	Used: ed.data.resmsg.total_used,
		// 	surplus: ed.data.resmsg.total_available,
		// 	msg: '当前key正常'
		// })
		return {
			code: 0,
			text
		}
	} else {
		// if (ed.code == 200) {
		// 	console.log(ed.data.resmsg.total_available);
		// 	if (ed.data.resmsg.total_used >= ed.data.resmsg.total_granted) {
		// 		await db.collection('apiKey').doc(String(apikey.data[0]._id)).update({
		// 			Used: ed.data.resmsg.total_used,
		// 			surplus: ed.data.resmsg.total_available,
		// 			is_open: 0,
		// 			msg: '当前key额度已满'
		// 		})
		// 	}
		// } else {
		await db.collection('apiKey').doc(String(apikey.data[0]._id)).update({
			is_open: 0,
			msg: '状态异常，请检查'
		})
		// }
		return {
			code: 400,
			msg: '网络繁忙！',
			data: openai_res
		}
	}
};
